# deepseek_model.py
import re
import requests
from typing import List, Dict, Optional, Any
from openai import OpenAI
from app.config import DEEPSEEK_API_KEY, logger


from app.services.models.base import BaseModel

class DeepSeekModel(BaseModel):
    """DeepSeek 模型调用封装"""

    def __init__(self, api_key: str = None, model: str = "deepseek-chat"):
        """
        初始化 DeepSeek 模型

        Args:
            api_key: DeepSeek API 密钥
            model: 使用的模型名称，默认为 deepseek-chat
        """
        # 如果没有提供api_key，则使用环境变量中的配置
        if api_key is None:
            api_key = DEEPSEEK_API_KEY
        
        self.api_key = api_key
        self.model = model
        self.endpoint = "https://api.deepseek.com/v1"

    def generate_response(self, messages: List[Dict[str, str]], tools: Optional[List[Dict[str, Any]]] = None, tool_choice: str = "auto", temperature: float = 0.1, **kwargs) -> Any:
        """
        调用 DeepSeek API 生成响应

        Args:
            system_prompt: 系统提示词
            user_prompt: 用户提示词
            temperature: 生成温度，控制随机性 (0-1)，默认0.1保证稳定性

        Returns:
            模型生成的响应文本
        """
        client = OpenAI(
            base_url=self.endpoint,
            api_key=self.api_key,
        )
        try:
            response = client.chat.completions.create(
                        model = self.model,
                        messages=messages,
                        tools = tools,
                        tool_choice = tool_choice,
                        temperature=temperature,
                        max_tokens=2000
                    )
            # 提取模型返回的内容
            return response.choices[0]

        except requests.exceptions.RequestException as e:
            raise Exception(f"API请求失败: {str(e)}")
        except KeyError as e:
            raise Exception(f"API响应解析失败: {str(e)}")
        except Exception as e:
            raise Exception(f"未知错误: {str(e)}")